---
import { createElement } from 'react';
import { renderToString } from 'react-dom/server';
import { Parser } from '@asyncapi/parser';
import { AvroSchemaParser } from '@asyncapi/avro-schema-parser';
import fs from 'fs';

import '@asyncapi/react-component/styles/default.min.css';
import js from '@asyncapi/react-component/browser/standalone/without-parser.js?url';
import { AsyncApiComponentWP, type ConfigInterface } from '@asyncapi/react-component';
import VerticalSideBarLayout from '@layouts/VerticalSideBarLayout.astro';
import Config from '@utils/eventcatalog-config/catalog';
import { Page } from './_[filename].data';
import { getAbsoluteFilePathForAstroFile } from '@utils/files';

export const prerender = Page.prerender;
export const getStaticPaths = Page.getStaticPaths;

// Get data
const { collection, data, filePath, filename, path: relativeSpecPath } = await Page.getData(Astro);

const fileName = filename || 'asyncapi.yaml';
const pathToSpec = getAbsoluteFilePathForAstroFile(filePath, fileName);
const fileExists = fs.existsSync(pathToSpec);
const isRemote = relativeSpecPath.includes('https://');
let content = '';

if (fileExists && !isRemote) {
  content = fs.readFileSync(pathToSpec, 'utf8');
}

if (isRemote) {
  // Fetch the content from the remote path
  content = await fetch(relativeSpecPath).then((res) => res.text());
}

// AsyncAPI parser will parser schemas for users, they can turn this off.
const parseSchemas = Config?.asyncAPI?.renderParsedSchemas ?? true;
const parsed = await new Parser({ schemaParsers: [AvroSchemaParser()] }).parse(content, { parseSchemas });
const stringified = parsed.document?.json();
const config: ConfigInterface = { show: { sidebar: true, errors: true } };

const component = createElement(AsyncApiComponentWP, { schema: { stringified }, config });
const renderedComponent = renderToString(component);

// Capitalize the first letter of a string
const pageTitle = `${collection} | ${data.name} | AsyncApi Spec`.replace(/^\w/, (c) => c.toUpperCase());

// Index only the latest version
const pagefindAttributes =
  data.version === data.latestVersion
    ? {
        'data-pagefind-body': '',
        'data-pagefind-meta': `title:${pageTitle}`,
      }
    : {};
---

<VerticalSideBarLayout title={pageTitle}>
  <div {...pagefindAttributes}>
    {
      // Currently, Pagefind does not index metadata (such as the title),
      // so we need to ensure it is included as text on the page.
      // https://github.com/CloudCannon/pagefind/issues/437
    }
    <h2 class="hidden">{pageTitle}</h2>
    <div id="asyncapi" class="md:pr-14" set:html={renderedComponent} />
  </div>
</VerticalSideBarLayout>

<script is:inline src={js}></script>
<script define:vars={{ schema: stringified, config }}>
  const root = document.getElementById('asyncapi');
  AsyncApiStandalone.hydrate({ schema, config }, root);
</script>

<style>
  #asyncapi {
    @media screen and (min-width: 1417px) {
      .sidebar {
        z-index: 1 !important;
      }
    }

    .aui-root .z-10 {
      z-index: 8;
    }
  }
</style>
